package com.googlecode.jlogindexer;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

import com.googlecode.jlogindexer.document.LogDocument;
import com.googlecode.jlogindexer.utils.JsonUtils;
import com.googlecode.jlogindexer.utils.SolrUtils;

public class JLogAppender extends AppenderSkeleton{

	private String solrUrl;
	
	private SolrUtils solrUtils=null;
	
	public String getSolrUrl() {
		return solrUrl;
	}

	public void setSolrUrl(String solrUrl) {
		this.solrUrl = solrUrl;
	}

	@Override
	public void activateOptions() {
			solrUtils=new SolrUtils(solrUrl);
			solrUtils.initServer();
	}
	
	@Override
	protected void append(LoggingEvent loggingEvent) {
		// TODO Use a log4j 
		// TODO Initialize a Solj object and 
		System.err.println("Server is Available??"+solrUtils.isServerAvailable());
		if (solrUtils.isServerAvailable()){
			System.err.println("YESSSSSSSSS  Server is Available");
			String jsonString=this.layout.format(loggingEvent);
			System.out.println(" TO BE COMMENTED JSON STRING :::"+jsonString);
			System.err.println("SOOOOOOOPERRRERRR Server is now Available.......");
			LogDocument logDocument = JsonUtils.mapJsonStringToLogDocument(jsonString);
			if (logDocument!=null){
				System.out.println("Adding document to SOLR......");
				solrUtils.addDocumentToSolr(logDocument);
			}
		}
		//TODO Comment this guy out.. Debugging purpose
//		else{
//			System.err.println("Server is NOOOTTTT Available right now.....");
//		}
				
		
		
	}

	public void close() {
		solrUtils.shutDownServer();
	}

	public boolean requiresLayout() {
		return true;
	}

	
	

}
